package com.eight.VoteController;

import com.eight.entity.Picture;
import com.eight.entity.VoteUser;
import com.eight.voteServer.PictureServer;
import com.eight.voteServer.VoteUserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import net.sf.json.JSONObject;
import java.util.Date;
import java.util.Properties;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class VoteUserController {

    @Autowired
    private VoteUserServer voteUserServer;

    @Autowired
    private PictureServer pictureServer;


    /**
     * 生成四位随机数
     */
    public String generateWord() {

        String[] beforeShuffle = new String[] { "2", "3", "4", "5", "6", "7",
                "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
                "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z" };
        List<String> list = Arrays.asList(beforeShuffle);
        Collections.shuffle(list);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
        }
        String afterShuffle = sb.toString();
        String result = afterShuffle.substring(5, 9);

        return result;
    }

    /**
     * 发邮件核心代码
     * 0 抱歉，您已经投过票了
     * 1 请您稍等，验证码正在发送
     */
    public static String myEmailAccount = "2376539013@qq.com";
    public static String myEmailPassword = "evntqveglihfebhd";//不能输入自己的真实密码，应该是授权码。
    public static String myEmailSMTPHost = "smtp.qq.com";

    @ResponseBody
    @RequestMapping(value = "sendEmail")
    public int senEmail(@RequestBody JSONObject jsonParam, HttpServletRequest request) throws Exception {

        String receiveMailAccount=jsonParam.getString( "email" );
        String username=jsonParam.getString( "username" );

        VoteUser voteUser=voteUserServer.findVoteUserByEmail(receiveMailAccount);

        if(voteUser==null||voteUser.getProof()==null) {


            VoteUser voteUser1=new VoteUser();
            voteUser1.setEmail( receiveMailAccount );
            voteUser1.setUsername( username );

            voteUserServer.save( voteUser1 );

            VoteUserController voteUserController=new VoteUserController();

            String code = voteUserController.generateWord();
            HttpSession session1=request.getSession();
            session1.setAttribute( "code",code );

            //String receiveMailAccount = "3310056607@qq.com";

            Properties props = new Properties();
            props.setProperty( "mail.transport.protocol", "smtp" );
            props.setProperty( "mail.smtp.host", myEmailSMTPHost );
            props.setProperty( "mail.smtp.auth", "true" );


            final String smtpPort = "465";
            props.setProperty( "mail.smtp.port", smtpPort );
            props.setProperty( "mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory" );
            props.setProperty( "mail.smtp.socketFactory.fallback", "false" );
            props.setProperty( "mail.smtp.socketFactory.port", smtpPort );


            Session session = Session.getInstance( props );
            session.setDebug( true );
            MimeMessage message = createMimeMessage( code, session, myEmailAccount, receiveMailAccount );

            Transport transport = session.getTransport();


            transport.connect( myEmailAccount, myEmailPassword );

            transport.sendMessage( message, message.getAllRecipients() );

            transport.close();

            return 1;

        }


        return 0;
    }

    /**
     * 创建一封只包含文本的简单邮件
     *
     * @param session     和服务器交互的会话
     * @param sendMail    发件人邮箱
     * @param receiveMail 收件人邮箱
     * @return
     * @throws Exception
     */
    public static MimeMessage createMimeMessage(String code ,Session session, String sendMail, String receiveMail) throws Exception {
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人
        message.setFrom(new InternetAddress(sendMail, "小蛾", "UTF-8"));

        // 3. To: 收件人（可以增加多个收件人、抄送、密送）
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "你好", "UTF-8"));

        // 4. Subject: 邮件主题
        message.setSubject("本次活动的验证码", "UTF-8");

        VoteUserController voteUserController=new VoteUserController();


        // 5. Content: 邮件正文（可以使用html标签）
        message.setContent(code, "text/html;charset=UTF-8");
        // 6. 设置发件时间
        message.setSentDate(new Date());

        // 7. 保存设置
        message.saveChanges();

        return message;
    }


    /**
     * 成功提交
     * @param jsonParam
     * @param request
     * @param id
     * @return 1  成功提交
     *         0  提交失败
     */
    @ResponseBody
    @RequestMapping(value = "codeEmail{id}")
    public int codeEmail(@RequestBody JSONObject jsonParam, HttpServletRequest request, @PathVariable("id") int id)  {

        String email=jsonParam.getString( "email" );
        String username=jsonParam.getString( "username" );
        String code=jsonParam.getString("code"  );

        HttpSession session = request.getSession();
        String code1 = (String) session.getAttribute("code");

        //如果验证成功
        if(code1.equalsIgnoreCase( code )){

            VoteUser voteUser=voteUserServer.findVoteUserByEmail( email );
            VoteUser voteUser1=new VoteUser();
            voteUser1.setVid( voteUser.getVid() );
            voteUser1.setProof( "1 ");
            voteUserServer.save( voteUser1 );

            Picture picture=pictureServer.findByPictureId(id);
            Picture picture1=new Picture();
            picture1.setId( picture.getId() );
            int a=picture.getVotenumber();
            picture1.setVotenumber( a+1 );
            pictureServer.save( picture1 );


            return 1;
        }



        return 0;
    }


}
